import datetime
from contextlib import contextmanager
from psycopg2 import pool
from psycopg2.extras import RealDictCursor

from bot.enterprise_wechat_gpt.config.conf import *
from bot.enterprise_wechat_gpt.util.constant.hidden_character import *


class PostgreSql:
    def __init__(self):
        self._connection_pool = None

    def initialize_connection_pool(self):
        self._connection_pool = pool.ThreadedConnectionPool(
            1,
            20,
            host=profile_["postgre"]["host"],
            port=80,
            user="LTAI5tMsnFz7WRxKJyBDK5uv",
            password="SZxfgbrWpDYaHOR4HsU5ENxDOw6Xxt",
            database="screen",
            keepalives=1,
            keepalives_idle=300,
            keepalives_interval=10,
            keepalives_count=15,
        )
        logging.info(f"{profile_['postgre']['host']}:80 PostgreSql connection pool created successfully~")

    @contextmanager
    def get_resource(self, autocommit=True):
        if self._connection_pool is None:
            self.initialize_connection_pool()

        conn = self._connection_pool.getconn()
        conn.autocommit = autocommit
        cursor = conn.cursor(cursor_factory=RealDictCursor)
        try:
            yield cursor, conn
        finally:
            cursor.close()
            self._connection_pool.putconn(conn)

    def shutdown_connection_pool(self):
        if self._connection_pool is not None:
            self._connection_pool.closeall()


postgre_sql = PostgreSql()


def update_activate_data(wx_id, receive_msg, agent_last_msg):
    with postgre_sql.get_resource() as (cursor, conn):
        now = datetime.datetime.now()
        yesterday = now.date() - datetime.timedelta(days=1)
        agent_last_msg = agent_last_msg.replace(jr_hidden_character.replace(" ", ""), jr_hidden_character)
        agent_last_msg = agent_last_msg.replace(jt_hidden_character.replace(" ", ""), jt_hidden_character)
        sql = f"update public.wechat_activate set receive_msg='{receive_msg}', receive_time='{now}' " \
               f"where wx_id='{wx_id}' and send_msg='{agent_last_msg}' "
        logging.info(f"sql = {sql}")
        cursor.execute(sql)
        logging.info(f"群发激活收到用户消息，更新群发记录信息成功 wx_id:{wx_id}")


if __name__ == '__main__':
    with postgre_sql.get_resource() as (cursor, conn):
        cursor.execute("select * from public.breakpoint_data limit 10")
        results = cursor.fetchall()
        print(results)
